from django.shortcuts import render
from .models import *
from rest_framework.views import APIView
from django.contrib.auth.hashers import make_password,check_password
from all.commin import get_redis_conn
from django.core.paginator import Paginator
from .ser import *
from rest_framework.response import Response
# Create your views here.

class NewAPI(APIView):

    def get(self,request):
        id = request.GET.get('id')
        userid = request.GET.get('userid')
        if not id:
            cpage = request.GET.get('cpage')
            print(cpage)
            new = News.objects.all()
            p = Paginator(new,2)
            alsl = p.page(cpage)
            ser = NewsSer(alsl,many=True)
            return Response({"code":200,"list":ser.data,"num":p.num_pages})
        else:
            nwe = News.objects.filter(id=id).first()
            ser = NewsSer(nwe)
            conn = get_redis_conn()
            c = conn.hincrby(userid,id)
            if c:
                c = int(c)
            if c > 3:
                return Response({"code":299,"mes":"不能访问"})
            return Response({"code":200,"list":ser.data})

class UserAPI(APIView):
    def post(self,request):
        password = request.data.get('password')
        username = request.data.get('username')
        user = User.objects.filter(username=username).first()
        if user:
            if user.password == password:
                return Response({"code":200,"userid":user.id})
        return Response({"code":10010,"mes":"不正确"})




































